package service

import (
	"gorm.io/gorm"
	"shop-bean/dto"
	"shop-bean/vo"
	"shop-common/library/variables"
	"shop-service/repository"
	"strconv"
	"strings"
)

type IShippingTemplatesNoDeliveryService interface {
	FindNoDelivery(tempId uint) ([]*dto.ShippingTemplatesDoDeliveryDTO, error)
	BatchDelete(db *gorm.DB, ids []uint) error
}

type ShippingTemplatesNoDeliveryService struct {
	db         *gorm.DB
	repository repository.IShippingTemplatesNoDeliveryRepository
}

func NewShippingTemplatesNoDeliveryService() IShippingTemplatesNoDeliveryService {
	return &ShippingTemplatesNoDeliveryService{
		db:         variables.GormDB(),
		repository: repository.NewShippingTemplatesNoDeliveryRepository(),
	}
}

func (s *ShippingTemplatesNoDeliveryService) FindNoDelivery(tempId uint) (list []*dto.ShippingTemplatesDoDeliveryDTO, err error) {
	rows, err := s.repository.FindGroup(s.db, tempId)
	if err != nil {
		return nil, err
	}
	for _, obj := range s.concatCity(s.splitGroupConcat(rows)) {
		list = append(list, obj)
	}

	return list, nil
}

//分组切割cityId
func (s *ShippingTemplatesNoDeliveryService) splitGroupConcat(rows []*vo.ShippingTemplatesNoDeliveryVO) (list []*dto.TempDoDelivery) {
	for _, row := range rows {
		var children []*dto.RegionDTO
		if row.ProvinceId > 0 {
			for _, item := range strings.Split(row.CityIdStr, ",") {
				intNum, _ := strconv.Atoi(item)
				children = append(children, &dto.RegionDTO{
					CityId: uint(intNum),
				})
			}
		}

		list = append(list, &dto.TempDoDelivery{
			UniqId:     row.UniqId,
			ProvinceId: row.ProvinceId,
			City:       children,
			NameStr:    row.NameStr,
		})
	}

	return list
}

// map去重基本信息
func (s *ShippingTemplatesNoDeliveryService) concatCity(rows []*dto.TempDoDelivery) map[string]*dto.ShippingTemplatesDoDeliveryDTO {
	var mapDto = make(map[string]*dto.ShippingTemplatesDoDeliveryDTO)
	for _, item := range rows {
		if mapDto[item.UniqId] != nil {
			if mapDto[item.UniqId].PlaceName == "" {
				mapDto[item.UniqId].PlaceName = mapDto[item.UniqId].PlaceName + item.NameStr
			} else {
				mapDto[item.UniqId].PlaceName = mapDto[item.UniqId].PlaceName + ";" + item.NameStr
			}
			mapDto[item.UniqId].Region = append(mapDto[item.UniqId].Region, &dto.RegionDTO{
				CityId:   item.ProvinceId,
				Children: item.City,
			})
		} else {
			mapDto[item.UniqId] = &dto.ShippingTemplatesDoDeliveryDTO{
				Region: []*dto.RegionDTO{{
					CityId:   item.ProvinceId,
					Children: item.City,
				}},
				PlaceName: item.NameStr,
				UniqId:    item.UniqId,
			}
		}
	}

	return mapDto
}

func (s *ShippingTemplatesNoDeliveryService) BatchDelete(db *gorm.DB, ids []uint) error {
	return s.repository.BatchDelete(db, ids)
}
